import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Loading } from 'element-ui'
import { getToken } from '@/utils/auth'
// import allPermission from '@/utils/allPermission'
NProgress.configure({ easing: 'linear', speed: 500, showSpinner: true })

/**
 * 白名单
 */
const whiteList = ['login', 'password', 'register', 'company', 'updateRecord', 'noPermission', 'helpDocsIndex', 'appH5Download', 'legaAgreement']
let loadingInstance = null
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  loadingInstance = Loading.service({
    fullscreen: true,
    text: '页面渲染中...',
    customClass: 'common-loading'
  })
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
      if (loadingInstance) {
        loadingInstance.close()
      }
    } else {
      try {
        const userInfo = await store.dispatch('getInfo')
        const roles = userInfo.roles
        /* if (to.name !== 'noPermission' && !allPermission.hasMenu(to.name)) {
          next(`/noPermission?permission=${to.name}&menuName=${to.meta.title}`)
          return
        }*/
        await store.dispatch('GenerateRoutes', { roles })
        next()
      } catch (error) {
        console.log(error)
        await store.dispatch('logout')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
        if (loadingInstance) {
          loadingInstance.close()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.name) !== -1) {
      /**
       * 白名单
       */
      next()
    } else {
      /**
       * 跳转至登录
       */
      next(`/login?redirect=${to.path}`)
      NProgress.done()
      if (loadingInstance) {
        loadingInstance.close()
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done()
  if (loadingInstance) {
    loadingInstance.close()
  }
})
